import { defineEventHandler, readMultipartFormData } from 'h3'
import * as mammoth from 'mammoth'
import * as fs from 'fs'
import * as path from 'path'
import * as os from 'os'
import WordExtractor from 'word-extractor'

export default defineEventHandler(async (event) => {
  try {
    const files = await readMultipartFormData(event)
    if (!files || files.length === 0) {
      throw new Error('No file uploaded')
    }

    const file = files[0]
    if (!file.filename) {
      throw new Error('Invalid filename')
    }
    const filename = file.name || file.filename || 'uploaded-file'
    const tempPath = path.join(os.tmpdir(), filename)
    
    // 写入临时文件
    await fs.promises.writeFile(tempPath, file.data)
    
    let textContent = ''
    
    try {
      if (file.filename.endsWith('.docx')) {
        // 处理 .docx 文件
        const result = await mammoth.extractRawText({ path: tempPath })
        textContent = result.value
      } else if (file.filename.endsWith('.doc')) {
        // 处理 .doc 文件
        const extractor = new WordExtractor()
        const extracted = await extractor.extract(tempPath)
        textContent = extracted.getBody()
      } else {
        throw new Error('Unsupported file format. Please use .doc or .docx files.')
      }
    } finally {
      // 清理临时文件
      try {
        await fs.promises.unlink(tempPath)
      } catch (e) {
        console.error('Error cleaning up temp file:', e)
      }
    }

    return {
      success: true,
      text: textContent,
      filename: file.filename
    }
  } catch (error: any) {
    console.error('File processing error:', error)
    throw createError({
      statusCode: 500,
      message: error.message || 'Failed to process file'
    })
  }
}) 